package com.huluobo.a2308douyindemo.demo

import android.os.CountDownTimer
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.OnLifecycleEvent

/**
 *  Created by LC on 2025/10/16.
 */
class CountDownManager(val time: Long) : LifecycleObserver {
    //声明倒计时的LiveData
    val timeLiveData = MutableLiveData<Int>()

    //倒计时
    private val countDownTimer = object : CountDownTimer(time, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            //当计时的时候,给LiveData赋值
            //子线程赋值
            timeLiveData.postValue((millisUntilFinished / 1000).toInt())
            //主线程赋值
//            timeLiveData.value = (millisUntilFinished / 1000).toInt()
        }

        override fun onFinish() {
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun tick() {
        Log.e("TagA", "开始计时")
        countDownTimer.start()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun finish() {
        Log.e("TagA", "结束计时")
        countDownTimer.cancel()
    }
}